package com.aco.party.web.controller.system;

import com.aco.party.enums.RoleEnum;
import com.aco.party.model.po.Role;
import com.aco.party.model.po.User;
import com.aco.party.model.vo.UserListResponse;
import com.aco.party.model.vo.UserQueryParam;
import com.aco.party.model.vo.common.*;
import com.aco.party.service.system.MessageService;
import com.aco.party.service.system.RoleService;
import com.aco.party.service.system.UserService;
import com.aco.party.util.PathUtil;
import com.aco.party.web.command.system.EditUserCommand;
import com.aco.party.web.validator.system.EditUserValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import static com.aco.party.util.WebModelUtil.convert2Pairs;
import static com.aco.party.util.WebModelUtil.getImgPath;

/**
 * Created by WangShijun on 2016/2/27.
 */
@Controller
@RequestMapping("/system")
public class ManageUsresController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ManageUsresController.class);

    private EditUserValidator validator = new EditUserValidator();

    private final String REDIRECTEDIT = "redirect:edit";

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private MessageService messageService;

    @RequestMapping(value = "/user/list",method = RequestMethod.GET)
    public String manageUsers(Model model,HttpServletRequest request,HttpServletResponse response){
        return "system/manageUsers";
    }

    @RequestMapping(value = "/user/list",method = RequestMethod.POST)
    @ResponseBody
    public Page<UserListResponse> getUsers(HttpServletRequest request,DataGridEntry entry){
        Page<UserListResponse> users = new Page<>();
        entry.webParamConvert();
        List<UserListResponse> userList = userService.getUsersByParam(new PageParam(entry.getOffset(), entry.getLimit()));
        users.setTotal(userService.getUserCount());
        users.setRows(userList);
        return users;
    }

    @RequestMapping(value = "/user/edit",method = RequestMethod.GET)
    public String showEditUser(@ModelAttribute EditUserCommand command,Model model){
        if(command.getId() != null){
            User po = userService.getUser(command.getId());
            if (po != null) {
                command.toCommand(po);
                Role role = roleService.getRoleByUserId(po.getId());
                if(role != null) {
                    command.setRole(role.getId());
                }
            }
            else
                model.addAttribute("no_obj", true);
        }
        setAtt(model);
        return "system/editUser";
    }

    @RequestMapping(value = "/user/edit",method = RequestMethod.POST)
    public String editUser(Model model,@ModelAttribute EditUserCommand command,@RequestParam(value = "file",required = false) MultipartFile file,BindingResult errors){
        validator.validate(command, errors);
        setAtt(model);
        if (!errors.hasErrors()) {
            User user = new User();
            command.toPo(user);
            if(command.getRole() != null){
                Role role = roleService.getRoleByUserId(user.getId());
                if(role != null) {
                    userService.decreaseRoles(user.getId(),role.getId());
                    userService.increaseRoles(user.getId(),command.getRole());
                }
            }
            userService.updateUser(user);
            model.addAttribute("no_error",true);
        }
        return "system/editUser";
    }

    @RequestMapping(value = "/user/add", method = RequestMethod.GET)
    public String showAdd(@ModelAttribute EditUserCommand command,Model model) {
        command.setStatus(1);
        setAtt(model);
        return "system/editUser";
    }

    @RequestMapping(value = "/user/add", method = RequestMethod.POST)
    public String add(Model model, @ModelAttribute EditUserCommand command, BindingResult errors,RedirectAttributes attributes) {
        validator.validate(command, errors);
        setAtt(model);
        if (errors.hasErrors()) {
            return "system/editUser";
        }
        User po = new User();
        command.toPo(po);
        userService.createUser(po);
        if(command.getRole() != null){
            userService.increaseRoles(po.getId(),command.getRole());
        }
        attributes.addAttribute("id", po.getId());
        attributes.addFlashAttribute("no_error", true);
        return REDIRECTEDIT;
    }

    @RequestMapping(value = "/user/delete",method = RequestMethod.POST)
    @ResponseBody
    public Response del(@RequestParam(required = true) Long id){
        logger.info("删除：" + id);
        userService.delete(id);
        return new Response();
    }

    private void setAtt(Model model){
        model.addAttribute("roles", convert2Pairs(roleService.findAllRoles()));
    }

    @RequestMapping(value = "/author/list",method = RequestMethod.GET)
    public String manageAuthor(Model model,HttpServletRequest request,HttpServletResponse response){
        return "system/manageAuthors";
    }

    @RequestMapping(value = "/author/list",method = RequestMethod.POST)
    @ResponseBody
    public Page<UserListResponse> getAuthors(DataGridEntry entry,UserQueryParam param){
        Page<UserListResponse> users = new Page<>();
        if(!StringUtils.isEmpty(param.getName())){
            param.setName("%" + param.getName() + "%");
        }
        entry.webParamConvert();
        param.setRoleId(3);
        List<UserListResponse> userList = userService.getAuthorsByParam(new PageParam(entry.getOffset(), entry.getLimit()), param);
        users.setTotal(userService.getAuthorsCountByParam(param));
        users.setRows(userList);
        return users;
    }

    @RequestMapping(value = "/author/changeRole",method = RequestMethod.POST)
    @ResponseBody
    public Response changeAuthorRole(Long id){
        UserWithRoleVo vo = userService.getUserWithRole(id);
        userService.decreaseRoles(vo.getId(), vo.getRoleId());
        userService.increaseRoles(vo.getId(), (long) RoleEnum.普通用户.getValue());
        return new Response();
    }

    @RequestMapping(value = "/author/changeHot",method = RequestMethod.POST)
    @ResponseBody
    public Response changeAuthorHot(Long id){
        UserWithRoleVo vo = userService.getUserWithRole(id);
        if(vo != null && vo.getExtra1() != null){
            if(vo.getExtra1() == 0){
                //1热门
                vo.setExtra1(1);
            }else{
                vo.setExtra1(0);
            }
            User updateUser = new User();
            updateUser.setId(vo.getId());
            updateUser.setExtra1(vo.getExtra1());
            userService.updateUser(updateUser);
        }
        return new Response();
    }

    @RequestMapping(value = "/author/audit",method = RequestMethod.GET)
    public String showAuditAuthor(Model model,HttpServletRequest request,HttpServletResponse response){
        return "system/auditAuthors";
    }

    @RequestMapping(value = "/author/audit",method = RequestMethod.POST)
    @ResponseBody
    public Page<UserListResponse> auditAuthor(Model model,DataGridEntry entry,HttpServletRequest request,HttpServletResponse response){
        Page<UserListResponse> users = new Page<>();
        entry.webParamConvert();
        UserQueryParam param = new UserQueryParam();
        param.setAudit(1);
        List<UserListResponse> userList = userService.getAuthorsByParam(new PageParam(entry.getOffset(), entry.getLimit()), param);
        users.setTotal(userService.getAuthorsCountByParam(param));
        users.setRows(userList);
        return users;
    }

    @RequestMapping(value = "/author/auditChange",method = RequestMethod.POST)
    @ResponseBody
    public Response auditChange(Long id,Long confirm){
        User user = new User();
        UserWithRoleVo vo = userService.getUserWithRole(id);
        user.setId(id);
        if(confirm == 1){
            //同意0
            user.setExtra2(0);
            userService.decreaseRoles(vo.getId(),vo.getRoleId());
            userService.increaseRoles(vo.getId(), (long)RoleEnum.专栏作者.getValue());
            userService.updateUser(user);
            //同意后发送站内信
            messageService.sendMsg(id,"系统消息","您的魔客专栏作者申请已经审批通过！");
        }else{
            //拒绝2
            user.setExtra2(2);
            userService.updateUser(user);
        }
        return new Response();
    }

    /**
     * 更新个人头像
     */
    @RequestMapping(value={"/changeUserPhoto"})
    @ResponseBody
    public Response changeUserPhoto(Model model,String photoUrl) throws Exception{
        Response response = new Response();
        User user = new User();
        user.setId(getCurrentUser().getId());
        user.setPhotoUrl(photoUrl);
        userService.updateUser(user);
        response.setData(user.getPhotoUrl());
        return response;
    }

}
